package com.coursebooking.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.coursebooking.model.Course;
import com.coursebooking.model.Review;
import com.coursebooking.model.Student;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Optional;

@Mapper
public interface ReviewRepository extends BaseMapper<Review> {
    
    @Select("SELECT * FROM review WHERE student_id = #{studentId} AND course_id = #{courseId}")
    Review selectByStudentAndCourse(@Param("studentId") Long studentId, @Param("courseId") Long courseId);
    
    @Select("SELECT * FROM review WHERE student_id = #{studentId}")
    List<Review> selectByStudentId(Long studentId);
    
    @Select("SELECT * FROM review WHERE course_id = #{courseId}")
    List<Review> selectByCourseId(Long courseId);
    
    @Select("SELECT * FROM review WHERE course_id = #{courseId} ORDER BY review_time DESC")
    List<Review> selectByCourseIdOrderByReviewTimeDesc(Long courseId);
    
    @Select("SELECT AVG(rating) FROM review WHERE course_id = #{courseId}")
    Double getAverageRatingByCourseId(@Param("courseId") Long courseId);
    
    @Select("SELECT COUNT(*) FROM review WHERE student_id = #{studentId} AND course_id = #{courseId}")
    int countByStudentAndCourse(@Param("studentId") Long studentId, @Param("courseId") Long courseId);
    
    // 为了保持兼容性，添加包装方法
    default Optional<Review> findByStudentAndCourse(Student student, Course course) {
        return Optional.ofNullable(selectByStudentAndCourse(student.getId(), course.getId()));
    }
    
    default List<Review> findByStudent(Student student) {
        return selectByStudentId(student.getId());
    }
    
    default List<Review> findByCourse(Course course) {
        return selectByCourseId(course.getId());
    }
    
    default List<Review> findByCourseOrderByReviewTimeDesc(Course course) {
        return selectByCourseIdOrderByReviewTimeDesc(course.getId());
    }
    
    default Double getAverageRatingByCourse(Course course) {
        return getAverageRatingByCourseId(course.getId());
    }
    
    default boolean existsByStudentAndCourse(Student student, Course course) {
        return countByStudentAndCourse(student.getId(), course.getId()) > 0;
    }
}